package com.lwl.blog.filter;

import com.lwl.blog.utils.MyBatisUtils;
import com.lwl.blog.utils.SqlSessionThreadLocal;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;


/**
 * 负责创建sqlsession对象放入threadlocal中
 */
@WebFilter(filterName = "SqlSessionFilter",urlPatterns = {
        "/SystemUserServlet/*", "/PageServlet/*",
        "/IndexServlet/*", "/UserServlet/*",
        "/static/static/discuss-publish.html",
        "/InvitationServlet/*"
})
public class SqlSessionFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        //创建sqlsess对象
        SqlSession sqlSession= MyBatisUtils.getSqlSession();
        //2.保存到threadlocal中
        SqlSessionThreadLocal.set(sqlSession);
        try {

            //3.放行，dofilter方法执行完servlet，service和dao，响应了
            chain.doFilter(req, resp);

            //4.处理异常，提交事物
            //commit有封装close会自动关闭sqlsession
            sqlSession.commit();

        }catch (Exception e){
            //事物回滚
            sqlSession.rollback();
            e.printStackTrace();
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
